package cn.atcoder.air.msg;

import cn.atcoder.air.exception.NoProviderException;
import cn.atcoder.air.transport.ClientTransportFactory;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author yangjunda1
 * @description
 * @date 5/9/19 5:16 PM
 */
public class MessageBuilder {

    public static BaseMessage buildHeartbeatRequest() {
        HeartbeatRequestMessage requestMessage = new HeartbeatRequestMessage();
        return requestMessage;
    }

    public static HeartbeatResponseMessage buildHeartbeatResponse(BaseMessage baseMessage) {
        HeartbeatResponseMessage responseMessage = new HeartbeatResponseMessage();
        responseMessage.setHeader(baseMessage.getHeader().clone());
        return responseMessage;
    }

    public static CallbackRequestMessage buildCallbackRequest(String clazzName, String methodName, Object[] args, Class[] argClasses) {
        CallbackRequestMessage requestMessage = new CallbackRequestMessage();
        requestMessage.setClazzName(clazzName);
        requestMessage.setMethodName(methodName);
        requestMessage.setArgs(args);
        requestMessage.setArgClasses(argClasses);
        return requestMessage;
    }

    public static CallbackResponseMessage buildCallbackResponse(BaseMessage baseMessage) {
        CallbackResponseMessage responseMessage = new CallbackResponseMessage();
        responseMessage.setHeader(baseMessage.getHeader().clone());
        return responseMessage;
    }

    public static CallbackResponseMessage buildNoProviderCallbackResponse(CallbackRequestMessage baseMessage) {
        CallbackResponseMessage responseMessage = new CallbackResponseMessage();
        responseMessage.setHeader(baseMessage.getHeader().clone());
        String ip = "";
        try {
            ip = InetAddress.getLocalHost().toString();
        } catch (UnknownHostException e) {
        }
        String errorMsg = "Execute method : ["+ baseMessage.getClazzName() +"." + baseMessage.getMethodName() + "] No alive provider of pinpoint address : [" + ip + "]!";
        responseMessage.setException(new NoProviderException(errorMsg));
        return responseMessage;
    }

}
